﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Mvc;

using ProjectBase.Core;
using ProjectBase.Core.Web;

namespace ProjectBase.Mvc.Views
{
    /// <summary>
    ///     Returns the JSON as the serialized datasource
    /// </summary>
    public class JsonCoreResult<T> : ActionResult
        where T : class
    {
        #region members
        T _data;
        Type _type;
        #endregion members

        public JsonCoreResult(T data)
        {
            _data = data;
            _type = typeof(T);
        }

        public virtual T Data
        {
            get { return _data; }
            set { _data = value; }
        }

        public virtual Type Type
        {
            get { return _type; }
            set { _type = value; }
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;

            response.Clear();
            response.ClearContent();

            response.ContentType = "text/plain";

            response.ContentEncoding = Encoding.Default;

            var ser = new DataContractJsonSerializer(Type);

            using (var mstrm = new MemoryStream())
            {
                ser.WriteObject(mstrm, Data);
                response.BinaryWrite(mstrm.ToArray());
            }
        }
    }
}